$(function () {
    load();
});
let classname = ''
let exportList = []

function load() {
    $('#info-table')
        .bootstrapTable(
            {
                method: 'GET', // 服务器数据的请求方式 get or post
                url: "/jzweb/eclassresource/getClassDetail", // 服务器数据的加载地址
                iconSize: 'outline',
                toolbar: '#info-table',
                striped: true, // 设置为true会有隔行变色效果
                dataType: "json", // 服务器返回的数据类型
                pagination: true, // 设置为true会在底部显示分页条
                singleSelect: false, // 设置为true将禁止多选
                // contentType : "application/x-www-form-urlencoded",
                // //发送到服务器的数据编码类型
                pageSize: 10, // 如果设置了分页，每页数据条数
                pageNumber: 1, // 如果设置了分布，首页页码
                //search : true, // 是否显示搜索框
                showColumns: false, // 是否显示内容下拉框（选择显示的列）
                sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者 "server"
                queryParamsType: "",
                // //设置为limit则会发送符合RESTFull格式的参数
                queryParams: function (params) {
                    let queryParams = {
                        pageNum: params.pageNumber,
                        pageSize: params.pageSize,
                        classId: sessionStorage.getItem('xqId'),
                    };
                    return queryParams;
                },
                responseHandler: function (res) {
                    if(res.data.records.length>0){
                        classname = res.data.records[0].classname
                    }
                    if (res.code !== '0') {
                        layer.msg('查询失败');
                        console.log(res.msg)
                        return false
                    }
                    return {
                        "total": res.data.total,//总数
                        "rows": res.data.records   //数据
                    };
                },
                formatNoMatches: function () {
                    return '未查询到班级信息，请重试';
                },
                onCheck: function (row) {
                    exportList.push(row.id)
                    console.log(exportList)
                },
                onUncheck: function (row) {
                    // 在这里可以根据需要处理数据，比如从某个数据集合中移除它
                    var index = exportList.indexOf(row.id); // 假设yourDataArray是你的数据源
                    if (index > -1) {
                        exportList.splice(index, 1); // 从数组中移除对应的对象
                    }
                    console.log(exportList)
                },
                onCheckAll: function (rows) {
                    for (var i = 0; i < rows.length; i++) {
                        let row = rows[i]
                        exportList.push(row.id);
                        //alert(rows[i].ResultName)
                    }

                },
                onUncheckAll: function (row) {
                    for (var i = 0; i < row.length + 1; i++) {
                        exportList.splice(i, row.length);
                        //alert(rows[i].ResultName)
                    }
                    exportList = []
                    console.log(exportList)
                },
                columns: [
                    {
                        checkbox: true
                    },
                    {
                        field: 'name',
                        title: '姓名',
                    },

                    {
                        field: 'sex',
                        title: '性别',
                        formatter: function (value, row, index) {
                            return `<sapn>${value==1?'男':'女'}</sapn>`
                        }
                    },
                    {
                        field: 'totalLearnTime',
                        title: '学习总时长',
                        formatter: function (value, row, index) {
                            return `<sapn style="color: #169bd5" onclick="learningTime('${row.id}')">${value}</sapn>`
                        }
                    },
                    {
                        field: 'latestLearnTime',
                        title: '最近学习时间'
                    },
                    {
                        field: 'questionNum',
                        title: '练题次数',
                        formatter: function (value, row, index) {
                            return `<sapn style="color: #169bd5" onclick="frequency('${row.id}')">${value}</sapn>`
                        }
                    },
                    {
                        field: 'practiceNum',
                        title: '练题总数量'
                    },
                    {
                        field: 'latestPracticeTime',
                        title: '最近练题时间'
                    },
                    {
                        title: '操作',
                        field: '',
                        align: 'center',
                        formatter: function (value, row, index) {
                            let encodedRow = encodeURIComponent(stringifyWithoutCircular(row));
                            let e = `<a class="btn btn-primary btn-sm" href="#" mce_href="#" title="修改" onclick="add('修改学生信息','${encodedRow}')">修改</a>`;
                            let d = `<a class="btn btn-danger btn-sm" href="#" title="删除" mce_href="#" onclick="remove('${encodedRow}')">删除</a>`;
                            let f = `<a class="btn btn-warning btn-sm " href="#" title="重置密码"  mce_href="#" onclick="resetPwd('${row.id}')">重置密码</a> `
                            return e + d + f;
                        }
                    }]
            });
}

function reLoad() {
    $('#info-table').bootstrapTable('refresh');
}

function handleexportList() {
    if (exportList.length == '0') {
        layer.msg('请勾选需要导出的数据')
        return false;
    }
    window.location.href = `/jzweb/eclassresource/exportClassDetail?ids=${exportList.join(',')}`
}

/**
 * 重置密码
 * @param {string} id
 * */
function resetPwd(id) {
    layer.open({
        title: '重置密码',
        content: `
           <div class="form-box">
               <label>密码：</label>
               <div class="layui-input-inline">
                  	<input id="password" name="password" class="form-control" placeholder="请至少输入8位密码">
               </div>
           </div>
        `,
        btn: ['确认', '取消']
        , yes: function (index, layero) {
            if($('#password').val().length<8){
                layer.msg('重置失败，请至少输入8位密码');
                return false
            }
            $.ajax({
                type:'post',
                url : `/jzweb/eclassresource/resetPwd`,
                contentType: "application/json",
                data:JSON.stringify({
                    id:id,
                    password:$('#password').val()
                }),
                success : function(r) {
                    if (r.code=='0') {
                        layer.msg(r.msg);
                        reLoad();
                    }else{
                        layer.msg(r.msg);
                    }
                }
            });
            //按钮【按钮一】的回调
            console.log('确认')
            layer.close(index)
        }
    });
}

/**
 * 编辑数据跳转
 * */
function edit(name) {
    layer.open({
        content: `
           <div class="form-box">
               <label>班级名称：</label>
               <div class="layui-input-inline">
                  <input id="name" name="name" value="${name}" type="text" required lay-verify="required" class="form-control" placeholder="请输入姓名">
               </div>
           </div>
        `,
        btn: ['确认', '取消']
        , yes: function (index, layero) {
            //按钮【按钮一】的回调
            console.log('确认')
            layer.close(index)
        }
    });
}


/**
 * 删除(根据id删除选项)
 * @param {string} id
 * */
function remove(row) {
    let data=JSON.parse(decodeURIComponent(row))
    layer.confirm('确定要删除选中的记录？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            type:'get',
            url : `/jzweb/eclassresource/quitClass?userId=${data.id}&classId=${data.classId}`,
            success : function(r) {
                if (r.code=='0') {
                    reLoad();
                    layer.msg('删除成功');
                    return;
                }else{
                    layer.msg('删除失败');
                }
            }
        });
    })
}


/**
 * 新增,修改学生
 * @param {string} title
 * @param {string} dataValue
 * */
const add = (title, dataValue) => {
    let data = ''
    if (dataValue && dataValue != "{}") { // 检查数据是否为空
        try {
            data = JSON.parse(decodeURIComponent(dataValue));
        } catch (error) {
            console.error("解析数据出错", error);
        }
    }
    let loading = layer.open({
        type: 1,
        area: ['400px', '360px'],
        title: title,
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        content: tmpData(data),
        success: function (layero, index) {
            layui.use(['form'], function () {
                var form = layui.form;
                // 初始化 select 控件

                $('#sex').val(data.sex || '');
                layui.form.render('select');

                // 监听提交事件
                form.on('submit(formDemo)', function (value) {
                    let tableValue = []
                    tableValue.push({
                        name: $('#name').val(),
                        mobile: $('#mobile').val(),
                        sex: $('#sex').val(),
                    })
                    if (!$('#sex').val()) return layer.msg('请选择性别')
                    let jsonData = {
                        // userId: $('#userId').val(),
                        // creatername:classname,
                        classname: classname,
                        studentVOList: tableValue,
                    }
                    if (title == '修改学生信息') {
                        $.ajax({
                            type: "POST",
                            url: "/jzweb/eclassresource/updateStu",
                            contentType: "application/json",
                            data: JSON.stringify({
                                id: JSON.parse(decodeURIComponent(dataValue)).id,
                                name: $('#name').val(),
                                mobile: $('#mobile').val(),
                                sex: $('#sex').val()
                            }),
                            success: function (data) {
                                if (data.code == '0') {
                                    // $("#classname").append('<option value="">请选择班级名称</option>');
                                    // data.data.map((item) => {
                                    //     $("#classname").append(`<option value=${item} data-school=${item}>${item}</option>`);
                                    // })
                                    layer.msg(data.msg);
                                    reLoad()
                                } else {
                                    layer.msg(data.msg);
                                }
                            }
                        });
                    } else {
                        submitAdd(jsonData)
                    }
                    layer.close(loading);
                    return false; // 阻止表单默认提交事件
                });

            });

        }
    });
}

const tmpData = (data) => {
    return `<div style="padding: 7px 20px">
               <form class="layui-form">
                    <input type="hidden" id="id" value="${data ? data.id : ''}">
                    <div class="form-box">
                        <label>姓名：</label>
                        <div class="layui-input-inline">
                           <input id="name" name="name" value="${data ? data.name : ''}" type="text" required lay-verify="required" class="form-control" placeholder="请输入姓名">
                        </div>
                    </div>
                    <div class="form-box">
                        <label>手机号：</label>
                        <div class="layui-input-inline">
                            <input id="mobile" name="mobile" type="text" value="${data ? data.mobile : ''}" required lay-verify="required" class="form-control" placeholder="请输入学号">
                        </div>
                    </div>
                    <div class="form-box">
                        <label>性别：</label>
                        <div class="layui-input-inline">
                           <select id="sex" name="sex"  lay-search="" required lay-verify="required" lay-filter="select-filter">
                               <option value="1">男</option>
                               <option value="2">女</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-box" style="text-align: center">
                        <button type="button" class="layui-btn" lay-submit lay-filter="formDemo">
                            确认
                        </button>
                    </div>
                </form>
            </div>
        `
}
const submitAdd = (jsonData) => {
    $.ajax({
        type: "POST",
        url: "/jzweb/eclassresource/inertClass",
        data: JSON.stringify(jsonData), // 将 JavaScript 对象转换为 JSON 字符串
        contentType: "application/json", // 指定发送的内容类型为 JSON
        success: function (data) {
            if (data.code == '0') {
                reLoad()
                layer.msg(data.msg);
                return
            } else {
                layer.msg(data.msg);
            }
        }
    });
}
/**
 * 批量导入
 * */
const exportsAll = () => {
    //文件
    layer.open({
        type: 1,
        area: ['500px', '400px'],
        title: '批量导入',
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        content: exposrtmp(),
        success: function (layero, index) {
            layui.use(['form', 'upload'], async function () {
                var form = layui.form;
                var upload = layui.upload;
                //上传
                upload.render({
                    elem: '#ID-upload-demo-drag',
                    url: '/jzweb/eclassresource/importStudent',
                    data: {classId: sessionStorage.getItem('xqId')},
                    exts: 'xls',
                    done: function (res) {
                        console.log(res)
                        if (res.code != "0") {
                            layer.msg(res.msg)
                        } else {
                            layer.msg('上传成功');
                            reLoad()
                            // $('#exampleTable').bootstrapTable('append', formData); 新增数据
                            layer.close(index)
                        }
                    }
                });

                form.on('submit(layedit-code-yes)', function (data) {
                    const mydata = data.field

                    //关闭
                    layer.close(index);
                });
            })
        }
    });

}

const exposrtmp = () => {
    return `
        <form class="layui-form layui-form-pane" style="width: 100%;height: 100%;padding: 10px;" id="myForm">
            <div class="layui-form-item">
            <label class="layui-form-label" style="width:auto;border: 0;">导入数据需按照模板填写信息 ，<a style="color: #169bd5" href="/jzweb/eclassresource/export">点击下载模板</a></label>
            </div>
            <div class="layui-form-item" style="height: calc(100% - 150px);">
        <div class="layui-upload-drag" style=" height: 100%; display: flex; justify-content: center;  align-items: center;
        flex-direction: column;" id="ID-upload-demo-drag">
          <i class="layui-icon layui-icon-upload"></i>
          <div class="layui-icon-upload-title">点击或将拖入删除</div>
          <div class="layui-hide" id="ID-upload-demo-preview">
             上传文件
             <input type="text" name="name" placeholder="" autocomplete="off" disabled>
          </div>
        </div>
          </div>
          <div class="layui-form-item" style="display: flex;    justify-content: center;">
<!--            <button class="layui-btn" type="button"  lay-submit lay-filter="layedit-code-yes">导入</button>-->
          </div>
        </form>
                `
}

/**
 * 导出
 * */
const exports = () => {
    console.log('导出')
    layer.confirm('确定要导出吗？', {
        btn: ['确定', '取消']
    }, function (layero) {
        // $.ajax({
        //     type:'get',
        //     url : `/secretKey/deletedById?id=${id}`,
        //     success : function(r) {
        //         if (r.code==='0') {
        //             layer.msg('导出成功');
        //             reLoad();
        //         }else{
        //             layer.msg('导出失败');
        //         }
        //     }
        // });
    })
}

/**
 * 学习时长跳转
 * @param {string} id
 * */
const learningTime = (id) => {
    sessionStorage.setItem('stuserId', id)
    let index = layer.open({
        type: 2,
        title: '学习信息',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['100%', '100%'],
        content: `/jzweb/eclassresource/studentInformation/studentInformation`// iframe的url
    });
    layer.full(index);
}

/**
 * 练题次数
 * @param {string} id
 * */
const frequency = (id) => {
    sessionStorage.setItem('stuserId', id)
    let index = layer.open({
        type: 2,
        title: '练题信息',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['100%', '100%'],
        content: `/jzweb/eclassresource/exercises/exercises`// iframe的url
    });
    layer.full(index);
}